﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Navigation;
using BathroomLocator.Phone.ViewModel;
using Microsoft.Phone.Shell;

namespace BathroomLocator.Phone.PivotContent
{
	public partial class BathroomListPage : UserControl
	{
		public BathroomListPage()
		{
			InitializeComponent();

			this.Loaded += this.OnBathroomListPageLoaded;
		}

		public BathroomListPageViewModel ViewModel
		{
			get { return this.DataContext as BathroomListPageViewModel; }
			set { this.DataContext = value; }
		}

		public event EventHandler<NavigationEventArgs> Navigate
		{
			add { this.ViewModel.Navigate += value; }
			remove { this.ViewModel.Navigate -= value; }
		}

		private static void SetApplicationState(string key, object value)
		{
			if (PhoneApplicationService.Current.State.ContainsKey(key))
			{
				PhoneApplicationService.Current.State.Remove(key);
			}

			PhoneApplicationService.Current.State.Add(key, value);
		}

		private void OnBathroomListPageLoaded(object sender, RoutedEventArgs e)
		{
			if (this.ViewModel != null)
			{
				this.ViewModel.LoadTable();
			}
		}

		private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (this.ViewModel != null)
			{
				var selector = sender as Selector;
				if ((selector == null) || (selector.SelectedIndex == -1))
					return;

				SetApplicationState("CurrentBathroomLocation", this.ViewModel.Table[selector.SelectedIndex]);
				
                this.ViewModel.NavigateTo(new Uri("/Pages/BathroomLocationDetailViewPage.xaml", UriKind.Relative));

				selector.SelectedIndex = -1;
			}
		}

		
	}
}
